<template>
  <div class="cu-common-layout">
    <div class="cu-common-layout-center">
      <el-row class="cu-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <el-col :span="4">
            <el-form-item label="校区品牌" prop="brand">
              <el-select v-model="query.brand" clearable required :style="{ width: '100%' }">
                <el-option :key="item.id" :label="item.fullName" :value="item.enCode" v-for="item in brandOptions" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="校区信息">
              <el-select v-model="query.campusId" placeholder="请选择校区" filterable clearable :loading="campusLoading" @focus="loadCampusOptions" :style="{ width: '100%' }">
                <el-option v-for="item in campusOptions" :key="item.id" :label="item.fullName + ' (' + item.enCode + ')'" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="沟通类型">
              <el-select v-model="query.type" placeholder="沟通类型" multiple clearable>
                <el-option-group v-for="group in typeOptions" :key="group.id" :label="group.fullName">
                  <el-option v-for="item in group.children" :key="item.id" :label="item.fullName" :value="item.enCode"></el-option>
                </el-option-group>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="受理时间">
              <el-date-picker v-model="query.acceptTime" type="datetimerange" value-format="timestamp" format="yyyy-MM-dd HH:mm:ss" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
              <el-button icon="el-icon-refresh-right" @click="reset()">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="cu-common-layout-main cu-flex-main">
        <div class="cu-common-head">
          <div>
            <el-button type="primary" icon="el-icon-plus" @click="addOrUpdateHandle()" v-has="'btn_add'">新增</el-button>
            <el-button type="text" icon="el-icon-download" @click="exportData()" v-has="'btn_download'">导出</el-button>
            <el-button type="text" icon="el-icon-delete" @click="handleBatchRemoveDel()" v-has="'btn_batchRemove'">批量删除</el-button>
          </div>
          <div class="cu-common-head-right">
            <el-tooltip effect="dark" content="刷新" placement="top">
              <el-link icon="icon-ym icon-ym-Refresh cu-common-head-icon" :underline="false" @click="reset()" />
            </el-tooltip>
            <screenfull isContainer />
          </div>
        </div>
        <custom-table v-loading="listLoading" :data="list" @sort-change="sortChange" has-c @selection-change="handleSelectionChange" size="small">
          <el-table-column label="校区品牌" width="80" prop="brand" align="center">
            <template slot-scope="scope">
              {{ scope.row.brand | dynamicCodeText(brandOptions) }}
            </template>
          </el-table-column>
          <el-table-column label="校区名称" width="200" prop="campusId" align="left" v-if="custom.hasP('campusId')" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.campusId | dynamicText(campusOptions) }}
            </template>
          </el-table-column>
          <el-table-column label="沟通类型" width="150" prop="type" align="left" v-if="custom.hasP('type')">
            <template slot-scope="scope">
              {{ scope.row.type | dynamicTreeCodeText(typeOptions) }}
            </template>
          </el-table-column>
          <el-table-column label="状态" width="80" prop="status" align="center" v-if="custom.hasP('status')">
            <template slot-scope="scope">
              {{ scope.row.status | dynamicText(statusOptions) }}
            </template>
          </el-table-column>
          <el-table-column label="沟通来源" width="80" prop="source" align="center" v-if="custom.hasP('source')">
            <template slot-scope="scope">
              {{ scope.row.source | dynamicText(sourceOptions) }}
            </template>
          </el-table-column>
          <el-table-column prop="contacts" label="联系人" width="100" align="left" v-if="custom.hasP('contacts')" />
          <el-table-column prop="mobile" label="联系电话" width="100" align="center" v-if="custom.hasP('mobile')" />
          <el-table-column prop="subject" label="沟通主题" width="200" align="left" v-if="custom.hasP('subject')" />
          <el-table-column prop="description" label="描述" align="left" v-if="custom.hasP('description')" show-overflow-tooltip />
          <el-table-column prop="acceptTime" label="受理时间" sortable="custom" align="center" v-if="custom.hasP('acceptTime')" :formatter="custom.tableDateTimeFormat" width="120" />
          <el-table-column prop="assigned" label="分配给" width="80" align="left" v-if="custom.hasP('assigned')" />
          <el-table-column label="操作" fixed="right" align="center" width="120">
            <template slot-scope="scope">
              <!--1：可编辑，2：已处理，需提审（3、特殊处理），4、审核通过 -->
              <el-button v-if="scope.row.status == 1" type="text" size="small" @click="addOrUpdateHandle(scope.row.id, false)" v-has="'btn_edit'">编辑</el-button>
              <el-button type="text" size="small" @click="AuditingHandle(scope.row.id)" v-has="'btn_review'" v-if="scope.row.status == 2 || scope.row.status == 3">审核</el-button>
              <el-button type="text" size="mini" @click="addOrUpdateHandle(scope.row.id, true)" v-has="'btn_detail'">详细</el-button>
              <el-button type="text" size="small" @click="handleDel(scope.row.id)" class="cu-table-delBtn" v-has="'btn_remove'">删除</el-button>
            </template>
          </el-table-column>
        </custom-table>
        <pagination :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize" @pagination="initData" />
      </div>
    </div>
    <custom-form v-if="formVisible" ref="CustomForm" @refresh="refresh" />
    <ExportBox v-if="exportBoxVisible" ref="ExportBox" @download="download" />
    <el-dialog title="审核" :visible.sync="dialogFormVisible" width="400px">
      <el-form :model="form" :rules="rules" ref="elForm">
        <el-form-item label="审核意见" :label-width="formLabelWidth" prop="status">
          <el-select v-model="form.status" placeholder="请选择审核意见" size="small">
            <el-option label="审核通过" value="4"></el-option>
            <el-option label="审核退回" value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmitAuditing">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import request from '@/utils/request'
import CustomForm from './Form/index.vue'
import ExportBox from './ExportBox'
import { getCampusSelector } from '@/api/campus/campus'
export default {
  components: { CustomForm, ExportBox },
  data() {
    return {
      name: 'campus.connect',
      showAll: false,
      query: {
        campusId: undefined,
        type: undefined,
        acceptTime: undefined,
        brand: undefined
      },
      list: [],
      listLoading: true,
      multipleSelection: [],
      total: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: ''
      },
      formVisible: false,
      exportBoxVisible: false,
      recordsVisible: false,
      columnList: [{ prop: 'brand', label: '校区品牌' }, { prop: 'campusCode', label: '校区编码' }, { prop: 'province', label: '省份' }, { prop: 'city', label: '城市' }, { prop: 'campusName', label: '校区简称' }, { prop: 'type', label: '沟通类型' }, { prop: 'subject', label: '沟通主题' }, { prop: 'statusText', label: '处理状态' }, { prop: 'sourceText', label: '沟通来源' }, { prop: 'contacts', label: '联系人' }, { prop: 'mobile', label: '联系电话' }, { prop: 'description', label: '描述' }, { prop: 'acceptTime', label: '受理时间' }, { prop: 'assigned', label: '分配给' }],
      campusOptions: [],
      campusLoading: false,
      typeOptions: [],
      brandOptions: [],
      statusOptions: [{ fullName: '处理中', id: '1' }, { fullName: '已处理', id: '2' }, { fullName: '特殊处理', id: '3' }, , { fullName: '已完结', id: '4' }],
      sourceOptions: [{ fullName: '400', id: 1 }, { fullName: '家校平台', id: 2 }, { fullName: '贝尔校长云', id: 3 }, { fullName: 'VIP群反馈', id: 4 }],
      dialogFormVisible: false,
      form: {
        id: '',
        status: ''
      },
      formLabelWidth: '120px',
      rules: {
        status: [
          {
            required: true,
            message: '请选择审核意见',
            trigger: 'change'
          }
        ]
      }
    }
  },
  computed: {},
  created() {
    this.initData()
    this.loadCampusOptions()

    this.$store.dispatch('base/getDictionaryData', { sort: 'ConnectType' }).then(res => {
      this.typeOptions = res
    })
    this.$store.dispatch('base/getDictionaryData', { sort: 'Brand' }).then(res => {
      this.brandOptions = res
    })
  },
  methods: {
    /**
     * 异步加载校区下拉选项
     * - 使用 getCampusSelector() 接口拉取校区数据
     * - 管理加载状态：campusLoading
     * - 错误时提示并清空选项
     */
    async loadCampusOptions() {
      try {
        this.campusLoading = true
        const params = {}
        if (this.query.brand) {
          params.brand = this.query.brand
        }
        // 指定返回字段，减少不必要传输
        params.fields = 'id,fullName'
        const res = await getCampusSelector(params)
        this.campusOptions = Array.isArray(res.data) ? res.data : []
      } catch (err) {
        console.error('加载校区下拉选项失败:', err)
        this.campusOptions = []
        this.$message && this.$message.error('校区选项加载失败')
      } finally {
        this.campusLoading = false
      }
    },
    sortChange({ column, prop, order }) {
      this.listQuery.sort = order == 'ascending' ? 'asc' : 'desc'
      this.listQuery.sidx = !order ? '' : prop
      this.initData()
    },
    initData() {
      this.listLoading = true
      let _query = {
        ...this.listQuery,
        ...this.query
      }
      let query = {}
      for (let key in _query) {
        if (Array.isArray(_query[key])) {
          query[key] = _query[key].join()
        } else {
          query[key] = _query[key]
        }
      }
      request({
        url: `/api/campus/connect`,
        method: 'GET',
        data: query
      }).then(res => {
        this.list = res.data.list
        this.total = res.data.pagination.total
        this.listLoading = false
      })
    },
    handleDel(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        type: 'warning'
      })
        .then(() => {
          request({
            url: `/api/campus/connect/${id}`,
            method: 'DELETE'
          }).then(res => {
            this.$message({
              type: 'success',
              message: res.msg,
              onClose: () => {
                this.initData()
              }
            })
          })
        })
        .catch(() => {})
    },
    AuditingHandle(id) {
      this.form.id = id
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['elForm'].resetFields()
      })
    },
    onSubmitAuditing() {
      this.$refs['elForm'].validate(valid => {
        if (valid) {
          this.$confirm('是否' + (this.form.status == 1 ? '退回' : '通过') + '该条投诉建议, 是否继续?', '提示', {
            type: 'warning'
          }).then(() => {
            request({
              url: `/api/campus/connect/${this.form.id}/${this.form.status}`,
              method: 'post'
            }).then(res => {
              this.$message({
                type: 'success',
                message: res.msg,
                onClose: () => {
                  this.dialogFormVisible = false
                  this.initData()
                }
              })
            })
          })
        }
      })
    },
    closedHandle(id) {
      this.$confirm('此操作将关闭该建议投诉, 是否继续?', '提示', {
        type: 'warning'
      })
        .then(() => {
          request({
            url: `/api/campus/connect/close/${id}`,
            method: 'post'
          }).then(res => {
            this.$message({
              type: 'success',
              message: res.msg,
              onClose: () => {
                this.initData()
              }
            })
          })
        })
        .catch(() => {})
    },
    handleSelectionChange(val) {
      const res = val.map(item => item.id)
      this.multipleSelection = res
    },
    handleBatchRemoveDel() {
      if (!this.multipleSelection.length) {
        this.$message({
          type: 'error',
          message: '请选择一条数据',
          duration: 1500
        })
        return
      }
      const ids = this.multipleSelection
      this.$confirm('您确定要删除这些数据吗, 是否继续？', '提示', {
        type: 'warning'
      })
        .then(() => {
          request({
            url: `/api/campus/connect/batchRemove`,
            method: 'POST',
            data: ids
          }).then(res => {
            this.$message({
              type: 'success',
              message: res.msg,
              onClose: () => {
                this.initData()
              }
            })
          })
        })
        .catch(() => {})
    },
    addOrUpdateHandle(id, isDetail) {
      this.formVisible = true
      this.$nextTick(() => {
        this.$refs.CustomForm.init(id, isDetail)
      })
    },

    exportData() {
      this.exportBoxVisible = true
      this.$nextTick(() => {
        this.$refs.ExportBox.init(this.columnList)
      })
    },
    download(data) {
      let query = { ...data, ...this.listQuery, ...this.query }
      request({
        url: `/api/campus/connect/Actions/Export`,
        method: 'GET',
        data: query
      }).then(res => {
        if (!res.data.url) return
        window.location.href = this.define.comUrl + res.data.url
        this.$refs.ExportBox.visible = false
        this.exportBoxVisible = false
      })
    },
    search() {
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: 'acceptTime'
      }
      this.initData()
    },
    refresh(isrRefresh) {
      this.formVisible = false
      if (isrRefresh) this.reset()
    },
    reset() {
      for (let key in this.query) {
        this.query[key] = undefined
      }
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: 'acceptTime'
      }
      this.initData()
    }
  }
}
</script>
